package com.masterclient.app.modules.shop.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.TimeUtil;
import com.masterclient.app.R;
import com.masterclient.app.modules.shop.adapter.StockFilterAveragePopAdapter;
import com.masterclient.app.modules.shop.adapter.StockFilterPopAdapter;
import com.masterclient.app.modules.shop.beans.StockChangeBean;
import java.util.Date;
import java.util.List;

public class StockFilterPopupWindow extends PopupWindow implements View.OnClickListener {

    public interface CallBack {
        void dismiss();

        void OnSelect(StockChangeBean.SearchSelectBean.specBean.defaultBean tabBean);

        void OnSelectTime(StockChangeBean.SearchSelectBean.specBean.defaultBean tabBean,String startTime, String endTime, String time);
    }

    private Activity context;
    private TextView tvBg;
    private TextView tvStartTime;
    private TextView tvEndTime;
    private TextView tvCancel;
    private TextView tvConfirm;
    private CallBack callBack;
    private int type = 1; //1：3等分；2：
    private String selectValue;
    private StockFilterAveragePopAdapter adapter;
    private List<StockChangeBean.SearchSelectBean.specBean.defaultBean> tabBeans;
    private StockChangeBean.SearchSelectBean.specBean.defaultBean timeTabBean = null;

    public StockFilterPopupWindow(Activity context, List<StockChangeBean.SearchSelectBean.specBean.defaultBean> tabBeans, int type, String selectValue, CallBack callBack) {
        super(context);
        this.context = context;
        this.callBack = callBack;
        this.type = type;
        this.selectValue = selectValue;
        this.tabBeans = tabBeans;
        initView(context);
    }

    private void initView(final Activity context) {
        LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View mView = mInflater.inflate(R.layout.stock_filter_popupwindow, null);
        RecyclerView recyclerView = mView.findViewById(R.id.recyclerView);
        tvBg = mView.findViewById(R.id.tv_bg);
        tvStartTime = mView.findViewById(R.id.tv_start_time);
        tvEndTime = mView.findViewById(R.id.tv_end_time);
        tvCancel = mView.findViewById(R.id.tv_cancel);
        tvConfirm = mView.findViewById(R.id.tv_confirm);
        View viewSelectTime = mView.findViewById(R.id.view_select_time);
        View viewBtn = mView.findViewById(R.id.view_btn);

        tvBg.setOnClickListener(this);
        tvStartTime.setOnClickListener(this);
        tvEndTime.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
        tvConfirm.setOnClickListener(this);

        for (int i =0; i<tabBeans.size();i++){
            tabBeans.get(i).isCheck = false;
        }

        if (type == 4) {
            viewSelectTime.setVisibility(View.VISIBLE);
            viewBtn.setVisibility(View.VISIBLE);
            GridLayoutManager layoutManager = new GridLayoutManager(context, 3);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                    super.onDraw(c, parent, state);
                }

                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    outRect.top = 0;
                    outRect.left = 0;
                    if ((parent.getChildLayoutPosition(view) + 1) % 3 == 0) {
                        outRect.right = 0;
                    } else {
                        outRect.right = ScreenUtils.dp2px(8);
                    }
                    outRect.bottom = ScreenUtils.dp2px(16);
                }
            });
            adapter = new StockFilterAveragePopAdapter(selectValue);
            recyclerView.setAdapter(adapter);
            adapter.setNewData(tabBeans);
            adapter.setOnItemClickListener((adapter12, view, position) -> {
                tabBeans.get(position).isCheck = true;
                for (int i =0; i<tabBeans.size();i++){
                    if (i != position){
                        tabBeans.get(i).isCheck = false;
                    }
                }
                adapter.updateSelectValue("");
                adapter12.notifyDataSetChanged();
                timeTabBean = tabBeans.get(position);
                tvStartTime.setText("开始时间");
                tvEndTime.setText("结束时间");
            });
        } else {
            viewSelectTime.setVisibility(View.GONE);
            viewBtn.setVisibility(View.GONE);
            ChipsLayoutManager chipsLayoutManager = ChipsLayoutManager.newBuilder(context)
                    .setChildGravity(Gravity.TOP)
                    .setScrollingEnabled(true)
                    .setGravityResolver(position -> Gravity.CENTER)
                    .setOrientation(ChipsLayoutManager.HORIZONTAL)
                    .setRowStrategy(ChipsLayoutManager.STRATEGY_DEFAULT)
                    .withLastRow(true)
                    .build();
            recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                    super.onDraw(c, parent, state);
                }

                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    outRect.top = 0;
                    outRect.left = 0;
                    outRect.right = ScreenUtils.dp2px(10);
                    outRect.bottom = ScreenUtils.dp2px(12);
                }
            });
            recyclerView.setLayoutManager(chipsLayoutManager);
            StockFilterPopAdapter adapter = new StockFilterPopAdapter(selectValue);
            recyclerView.setAdapter(adapter);
            adapter.setNewData(tabBeans);
            adapter.setOnItemClickListener((adapter1, view, position) -> callBack.OnSelect(tabBeans.get(position)));
        }

        //设置SelectPicPopupWindow的View
        this.setContentView(mView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置PopupWindow可触摸
        this.setTouchable(true);
        //设置非PopupWindow区域是否可触摸


        ColorDrawable dw = new ColorDrawable(0x00000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        this.setOnDismissListener(() -> {
            // TODO Auto-generated method stub
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_start_time:
                String birthDay = "";
                DatePickerPopDialog pickerPopWin = new DatePickerPopDialog.Builder(context, (year, month, day, dateDesc) -> {
                    timeTabBean = null;
                    for (int i =0; i<tabBeans.size();i++){
                        tabBeans.get(i).isCheck = false;
                    }
                    adapter.notifyDataSetChanged();
                    tvStartTime.setText(dateDesc);
                    tvStartTime.setTextColor(Color.parseColor("#141922"));
                }).textConfirm("确定") //text of confirm button
                        .textCancel("")
                        .btnTextSize(14) // button text size
                        .viewTextSize(15) // pick view text size
                        .colorConfirm(Color.parseColor("#629FFF"))//color of confirm button
                        .minYear(1900) //min year in loop
                        .maxYear(Integer.parseInt((TimeUtil.fmt.format(new Date()).toString().split("-"))[0]) + 1) // max year in loop
                        .showDayMonthYear(false) // shows like dd mm yyyy (default is false)
                        .dateChose(TextUtils.isEmpty(birthDay) ?
                                TimeUtil.fmt.format(new Date()).toString() : birthDay) // date chose when init popwindow
                        .build();
                pickerPopWin.showPopWin(context);
                break;
            case R.id.tv_end_time:
                String birthDay2 = "";
                DatePickerPopDialog pickerPopWin2 = new DatePickerPopDialog.Builder(context, (year, month, day, dateDesc) -> {
                    timeTabBean = null;
                    for (int i =0; i<tabBeans.size();i++){
                        tabBeans.get(i).isCheck = false;
                    }
                    adapter.notifyDataSetChanged();
                    tvEndTime.setText(dateDesc);
                    tvEndTime.setTextColor(Color.parseColor("#141922"));
                }).textConfirm("确定") //text of confirm button
                        .textCancel("")
                        .btnTextSize(14) // button text size
                        .viewTextSize(15) // pick view text size
                        .colorConfirm(Color.parseColor("#629FFF"))//color of confirm button
                        .minYear(1900) //min year in loop
                        .maxYear(Integer.parseInt((TimeUtil.fmt.format(new Date()).toString().split("-"))[0]) + 1) // max year in loop
                        .showDayMonthYear(false) // shows like dd mm yyyy (default is false)
                        .dateChose(TextUtils.isEmpty(birthDay2) ?
                                TimeUtil.fmt.format(new Date()) : birthDay2) // date chose when init popwindow
                        .build();
                pickerPopWin2.showPopWin(context);
                break;
            case R.id.tv_bg:
            case R.id.tv_cancel:
                dismiss();
                break;
            case R.id.tv_confirm:
                if (timeTabBean != null) {
                    callBack.OnSelectTime(timeTabBean,tvStartTime.getText().toString(), tvEndTime.getText().toString(), tvStartTime.getText().toString() + " 至 " + tvEndTime.getText().toString());
                } else {
                    if (TextUtils.isEmpty(tvStartTime.getText().toString()) || "开始时间".equals(tvStartTime.getText().toString())){
                        ToastUtil.showToast("请选择开始时间");
                        return;
                    }
                    if (TextUtils.isEmpty(tvEndTime.getText().toString()) || "结束时间".equals(tvEndTime.getText().toString())){
                        ToastUtil.showToast("请选择结束时间");
                        return;
                    }
                    if (!TextUtils.isEmpty(tvStartTime.getText().toString()) && !TextUtils.isEmpty(tvEndTime.getText().toString())) {
                        callBack.OnSelectTime(timeTabBean,tvStartTime.getText().toString(), tvEndTime.getText().toString(), tvStartTime.getText().toString() + " 至 " + tvEndTime.getText().toString());
                    }
                }
                dismiss();
                break;
        }
    }

    @Override
    public void showAsDropDown(View anchor) {
        if (Build.VERSION.SDK_INT >= 24) {
            Rect rect = new Rect();
            anchor.getWindowVisibleDisplayFrame(rect);
            Activity activity = (Activity) anchor.getContext();
            Rect outRect1 = new Rect();
            activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect1);
            int h = outRect1.height() - rect.bottom;
            setHeight(h);
        }
        super.showAsDropDown(anchor);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        callBack.dismiss();
    }
}





